﻿using BCCommon;
using BCDto.UploadHandleComponent;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace BCService.UploadHandleComponent
{
    public class UploadHandleBase:IUploadHandleBase
    {
        private readonly IServiceProvider serviceProvider;
        private static Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
        public UploadHandleBase(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
            if (keyValuePairs.Count == 0)
            {
                foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    if (type.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IUploadHandle)))
                    {
                        ConstructorInfo firstConstructor = type.GetTypeInfo().GetConstructors().FirstOrDefault();
                        //获取构造参数列表最多的构造方法
                        foreach (var constructor in type.GetTypeInfo().GetConstructors())
                        {
                            if (constructor.GetParameters().Length > firstConstructor.GetParameters().Length)
                            {
                                firstConstructor = constructor;
                            }
                        }

                        //提取构造参数
                        IEnumerable<object> constructorParameters = firstConstructor.GetParameters().Select(p => serviceProvider.GetService(p.ParameterType));
                        //构建服务实例
                        var service = Activator.CreateInstance(type, constructorParameters.ToArray());
                        keyValuePairs.Add(type.Name.Replace("Handle","").ToLower(), service);
                    }
                }
            }
        }
        /// <summary>
        /// 获取处理程序接口
        /// </summary>
        /// <param name="uploadFileDto">上传文件模型</param>
        /// <returns></returns>
        public IUploadHandle GetHandle(UploadFileDto uploadFileDto)
        {
            if (string.IsNullOrWhiteSpace(uploadFileDto.FolderName))
            {
                throw new ArgumentException("此上传文件缺少上传目录名称。");
            }
            return (IUploadHandle)keyValuePairs[uploadFileDto.FolderName];
        }
    }
}
